# getNobsForMatrixOfModels.R
# created 2012 Jul 25, 2012

getNobsForMatrixOfModels <- function(varNames, objectEnvir, objectSuffix = '.IV') {
  # This function takes a list of variable name stems and an environment in 
  # which estimated-model objects are stored.  It returns a matrix indicating 
  # the number of observations used to estimate each model-object.  The 
  # columns of the matrix are given by varNames.    
  if (! class(varNames) %in% 'character') {
    stop("varNames argument must be of class 'character'.")
  }
  if (any(duplicated(varNames))) {
    stop("varNames must not contain any duplicates.")
  }
  if (length(objectEnvir) %% length(varNames) != 0) {
    stop("Number of objects in objectEnvir is not a multiple of length(varNames).")
  }
  nrow <- length(ls(pat = paste0('^', varNames[1]), envir = objectEnvir))
  ncol <- length(varNames)
  out  <- matrix(NA, nrow = nrow, ncol = ncol, dimnames = list(NULL, varNames))
  for (varName in varNames) {    
    IVObjectNames <- sort(ls(pat = paste0('^', varName, objectSuffix), envir = objectEnvir))
    IVObjects <- lapply(IVObjectNames, get, envir = objectEnvir)
    out[, varName] <- sapply(IVObjects, nobs)
  }
  out
}    

